import { setFactoryMsgDTOList, setItem, setData, saveProduct, getLimit, formatDate, compareFactorySale, deleteDistib, setDTOList, onSet, setBatchData, getCode, setAdd, getValueArray, setEmptyArray, setArrayValue } from '@/views/sales/common/TableSaleMethods'
import { ajaxGet, ajaxPost, jsonPost } from '@/util'
import { Notice } from 'view-design'
export default ({
  state: {
    bargainData: [],
    getBgLmtData: [],
    getBgUnLmtData: [],
    form: {
      phone: '',
      phoneList: [{
        'value': '',
        'n': ''
      }],
      disribuTypeDelay: '1',
      isSet: '0',
      disribuType: '0',
      isCurrencyNum: '1',
      isStoreSet: '0',
      warningQuantity: 50,
      factoryTag: [],
      allDistributor: false,
      tag: '',
      name: '',
      propagate: '',
      date: [],
      integralDate: [],
      delayDate: [],
      currencyNum: '',
      limitNum: '',
      distribList: [],
      distribedList: [],
      delayDistribList: [],
      delayDistribedList: [],
      payDistribList: [],
      payDistribedList: [],
      list: [],
      isStoreType: true,
      storeNum: false,
      couponsList: [],
      provinceId: '',
      cityId: '',
      areaId: '',
      aaade: '',
      delayProvinceId: '',
      delayCityId: '',
      delayAreaId: '',
      delayAaade: '',
      phoneRemind: {
        allRemind: true,
        listRemind: [{
          isRemind: true,
          time: 2,
          text: '好胎不贵，不抢就亏，云店最新抢购活动来了，别忘了来抢哦'
        }, {
          isRemind: true,
          text: '抢购开始了，快来看有没中意规格，数量有限，来晚就没了'
        }, {
          isRemind: true,
          time: 12,
          text: '抢购快结束啦，客户常有，优惠价不常有，没抢的老板们快来抢最后几条底价轮胎'
        }]
      },
      payDistributorJoinType: 'WHOLE', // 支付方式是不是全部经销商
      payMethodTypeEnumList: ['THIRD'], // 支付方式
      payDistributorIdList: [], // 支付方式 制定经销商
      mainImg: [],
      isParcel: false,
      parcelContent: {
        factoryParcelTypeEnum: 'AMOUNT',
        amount: 0,
        num: 0
      }
    },
    storeCount: '',
    exceptionalStoreDTOList: '',
    searchForm: {
      brandId: null,
      ownerCategoryId: null,
      keyword: '',
      code: '',
      skuCode: ''
    },
    limitBrandNum: '',
    UnlimitBrandNum: ''
  },
  mutations: {
    setBargainStoreList (state, data) {
      state.form.list = data.map(item => {
        return {
          isChecked: false,
          value: item.value,
          name: item.text,
          num: '',
          totalNum: ''
        }
      })
    },
    changeRemind (state) {
      let list = state.form.phoneRemind.listRemind.filter(item => item.isRemind)
      state.form.phoneRemind.allRemind = !!list.length
    },
    changeRemindAll (state) {
      let status = JSON.parse(JSON.stringify(state.form.phoneRemind.allRemind))
      state.form.phoneRemind.listRemind.forEach(item => {
        item.isRemind = status
      })
    },
    setSetSearchEmpty (state) {
      state.searchForm.brandId = null
      state.searchForm.ownerCategoryId = null
      state.searchForm.keyword = ''
      state.searchForm.code = ''
      state.searchForm.skuCode = ''
    },
    onSetSearch (state, param) {
      state.searchForm.brandId = param.brandId
      state.searchForm.ownerCategoryId = param.ownerCategoryId
      state.searchForm.keyword = param.keyword
      state.searchForm.code = param.code
      state.searchForm.skuCode = param.skuCode
    },
    setBargainEmpty (state, param) {
      state.bargainData = []
      state.getBgLmtData = []
      state.getBgUnLmtData = []
      state.form = {
        phone: '',
        phoneList: [{
          'value': '',
          'n': ''
        }],
        isSet: '0',
        disribuType: '0',
        isCurrencyNum: '1',
        isStoreSet: '0',
        warningQuantity: 50,
        factoryTag: [],
        allDistributor: false,
        tag: '',
        name: '',
        propagate: '',
        date: [],
        integralDate: [],
        delayDate: [],
        currencyNum: '',
        limitNum: '',
        distribList: [],
        distribedList: [],
        delayDistribList: [],
        delayDistribedList: [],
        payDistribList: [],
        payDistribedList: [],
        list: [],
        isStoreType: true,
        storeNum: false,
        couponsList: [],
        provinceId: '',
        cityId: '',
        areaId: '',
        aaade: '',
        delayProvinceId: '',
        delayCityId: '',
        delayAreaId: '',
        delayAaade: '',
        phoneRemind: {
          allRemind: true,
          listRemind: [{
            isRemind: true,
            time: 2,
            text: '好胎不贵，不抢就亏，云店最新抢购活动来了，别忘了来抢哦'
          }, {
            isRemind: true,
            text: '抢购开始了，快来看有没中意规格，数量有限，来晚就没了'
          }, {
            isRemind: true,
            time: 12,
            text: '抢购快结束啦，客户常有，优惠价不常有，没抢的老板们快来抢最后几条底价轮胎'
          }]
        },
        payDistributorJoinType: 'WHOLE', // 支付方式是不是全部经销商
        payMethodTypeEnumList: ['THIRD'], // 支付方式
        payDistributorIdList: [], // 支付方式 制定经销商
        mainImg: [],
        isParcel: false,
        parcelContent: {
          factoryParcelTypeEnum: 'AMOUNT',
          amount: 0,
          num: 0
        }
      }
      state.exceptionalStoreDTOList = ''
      state.storeCount = ''
    },
    onAddPhoneBargain (state) {
      if (state.form.phoneList.length <= 9) {
        state.form.phoneList.push({
          value: '',
          n: ''
        })
      }
    },
    onAddReducePhoneBargain (state, index) {
      state.form.phoneList.splice(index, 1)
    },
    setQuality (state, param) {
      let type = 'getBgUnLmtData'
      if (param.isLimitBrand) {
        type = 'getBgLmtData'
      }
      for (let item of state[type]) {
        for (let todo of item.productSkuList) {
          if (param.acId == todo.acId) {
            todo.sellOutQuantity = Number(todo.sellOutQuantity) + Number(param.replenish)
            onSet(todo, item, 'sellOutQuantity')
          }
        }
      }
    },
    insertImportData (state, object) {
      if (object.type == '0') { // 限制品牌
        compareFactorySale(state.getBgLmtData, state.getBgUnLmtData, object)
        if (!state.getBgLmtData.length) {
          state.getBgLmtData = object.data
        }
      } else { // 非限制品牌
        compareFactorySale(state.getBgUnLmtData, state.getBgLmtData, object)
        if (!state.getBgUnLmtData.length) {
          state.getBgUnLmtData = object.data
        }
      }
    },
    bargainDeleteDistib (state, object) {
      let index = 'distribList'
      let index1 = 'distribedList'
      if (object.type == 'pay') {
        index = 'payDistribList'
        index1 = 'payDistribedList'
      }
      if (object.type == 'delay') {
        index = 'delayDistribList'
        index1 = 'delayDistribedList'
      }
      state.form[index1] = state.form[index1].filter(item => item.id !== object.item.id)
      state.form[index].unshift(object.item)
    },
    bargainDistib (state, object) {
      let index = 'distribList'
      let index1 = 'distribedList'
      if (object.type == 'pay') {
        index = 'payDistribList'
        index1 = 'payDistribedList'
      }
      if (object.type == 'delay') {
        index = 'delayDistribList'
        index1 = 'delayDistribedList'
      }
      state.form[index] = state.form[index].filter(item => item.id !== object.item.id)
      state.form[index1].push(object.item)
    },
    getBargainDetail (state, data) {
      state.exceptionalStoreDTOList = data.activityFactoryInfoDTO.exceptionalStoreDTOList
      state.storeCount = data.activityFactoryInfoDTO.storeCount
      state.form.tag = data.activityInfoDTO.promotionTagId
      state.form.name = data.activityInfoDTO.activityName
      state.form.propagate = data.activityFactoryInfoDTO.advertisingSlogan
      state.form.date = [new Date(data.activityInfoDTO.startDate), new Date(data.activityInfoDTO.endDate)]
      state.form.integralDate = [new Date(data.activityFactoryInfoDTO.activeLimitStartTime), new Date(data.activityFactoryInfoDTO.activeLimitEndTime)]
      state.form.delayDate = (data.activityFactoryInfoDTO.activeDelayStartTime && data.activityFactoryInfoDTO.activeDelayEndTime)
        ? [new Date(data.activityFactoryInfoDTO.activeDelayStartTime), new Date(data.activityFactoryInfoDTO.activeDelayEndTime)] : []
      state.form.disribuTypeDelay = '1' // 例外经销商没有全部
      state.form.limitNum = data.activityFactoryInfoDTO.commonLimitNumber
      state.form.isStoreType = !state.form.storeNum
      if (data.activityFactoryInfoDTO.mainImg && data.activityFactoryInfoDTO.mainImg !== '0') {
        state.form.mainImg = [{ imgUrl: data.activityFactoryInfoDTO.mainImg, status: 'finished' }]
      } else {
        state.form.mainImg = []
      }
      state.form.phoneList = data.activityFactoryInfoDTO.phoneList && data.activityFactoryInfoDTO.phoneList.map(item => {
        return {
          value: item,
          n: ''
        }
      })
      if (!state.form.phoneList) {
        state.form.phoneList = [{
          'value': '',
          'n': ''
        }]
      }
      state.form.isSet = data.activityFactoryInfoDTO.phoneList && data.activityFactoryInfoDTO.phoneList.length ? '1' : '0'
      state.form.disribuType = data.activityFactoryInfoDTO.distributorJoinTypeEnum == 'PART' ? '1' : '0'
      state.form.isCurrencyNum = data.activityFactoryInfoDTO.limitTypeEnum == 'GENERAL_STORE' ? '0' : '1'
      if (data.activityFactoryInfoDTO.exceptionalTypeEnum == 'STORE') {
        state.form.isStoreSet = '0'
      } else if (data.activityFactoryInfoDTO.exceptionalTypeEnum == 'DISTRIBUTOR') {
        state.form.isStoreSet = '1'
      } else {
        state.form.isStoreSet = '2'
      }
      state.form.exceptionalCount = data.activityFactoryInfoDTO.exceptionalCount
      state.form.warningQuantity = data.activityFactoryInfoDTO.warningQuantity
      state.form.distribedList = ((data.distributorList && data.distributorList) || []).map(item => {
        return {
          id: item.id,
          value: item.name,
          status: true
        }
      })
      state.form.delayDistribedList = (data.delayDistributorDTOList || []).map(item => {
        return {
          id: item.id,
          value: item.name,
          status: true
        }
      })
      state.form.payDistributorJoinType = data.activityFactoryInfoDTO.payDistributorJoinType
      state.form.payDistribedList = ((data.payDistributorDTOList && data.payDistributorDTOList) || []).map(item => {
        return {
          id: item.id,
          value: item.name,
          status: true
        }
      })
      state.form.payMethodTypeEnumList = data.activityFactoryInfoDTO.payMethodTypeEnumList ? data.activityFactoryInfoDTO.payMethodTypeEnumList : []
      // 手机提醒
      if (data.activityFactoryInfoDTO.factoryMsgDTOList) setFactoryMsgDTOList(state, data.activityFactoryInfoDTO.factoryMsgDTOList)
      state.form.phoneRemind.allRemind = data.activityFactoryInfoDTO.isOpenMsg
      !state.form.distribedList ? state.form.distribedList = [] : ''
      !state.form.payDistribedList ? state.form.payDistribedList = [] : ''
      if (data.activityFactoryInfoDTO.storeTypeLimitNumberDTOList) setDTOList(state, data.activityFactoryInfoDTO.storeTypeLimitNumberDTOList)
      // 包邮信息
      state.form.isParcel = data.activityFactoryInfoDTO.isParcel
      if (data.activityFactoryInfoDTO.isParcel) {
        const factoryParcelTypeEnum = data.activityFactoryInfoDTO.parcelContent.factoryParcelTypeEnum
        state.form.parcelContent.factoryParcelTypeEnum = factoryParcelTypeEnum
        if (factoryParcelTypeEnum === 'AMOUNT') {
          state.form.parcelContent.amount = data.activityFactoryInfoDTO.parcelContent.amount
        } else {
          state.form.parcelContent.num = data.activityFactoryInfoDTO.parcelContent.num
        }
      }
    },
    // bargainDelSale (state, param) {
    //   let type = ''
    //   if (param == 'limit') {
    //     type = 'getBgLmtData'
    //   } else if (param == 'unLimit') {
    //     type = 'getBgUnLmtData'
    //   }
    //   deleteValueArray(state[type], {
    //     index: 'checked',
    //     childName: 'productSkuList',
    //     status: true
    //   })
    //   setEmptyArray(state[type], {
    //     index: 'checked',
    //     childName: 'productSkuList'
    //   })
    //   getValueStatus(state[type], {
    //     index: 'checked',
    //     childName: 'productSkuList'
    //   })
    // },
    bargainGetSale (state, param) {
      if (param.type == 1) {
        // compareSaleGift(state.bargainData, state.getBgLmtData)
        // compareOther(state.bargainData, state.getBgUnLmtData, [], '不限品牌')
        let getdata = JSON.parse(JSON.stringify(state.bargainData))
        getValueArray(getdata, { index: 'checked', childName: 'productSkuList', status: false })
        setEmptyArray(getdata, { index: 'checked', childName: 'productSkuList' })
        setArrayValue(getdata, { index: 'checked', val1: false, childName: 'productSkuList' })
        let paramData = {
          shelfStatusEnum: 'ON',
          joinTypeEnum: 'PART',
          startDate: formatDate(state.form.date[0], true),
          endDate: formatDate(state.form.date[1], true),
          productSkuList: getLimit(getdata, param.type == 1),
          distributorIdList: (state.form.distribedList || []).map(item => {
            return item.id
          }),
          distributorJoinTypeEnum: state.form.disribuType == '0' ? 'WHOLE' : 'PART'
        }
        if (!paramData.productSkuList.length) {
          Notice.warning({
            title: '温馨提示',
            desc: '请选择主商品加入限制品牌'
          })
          return
        }
        saveProduct({
          productSkuList: paramData.productSkuList,
          activityId: param.id,
          self: param.self,
          type: param.type
        })
        // paramData.productSkuList.length && checkProduct(paramData)
        // if (getdata.length) {
        //   Notice.success({
        //     title: '温馨提示',
        //     desc: getProductData(getdata) + '加入限制品牌成功'
        //   })
        // }
        if (!state.getBgLmtData.length) { //首次为空
          // state.getBgLmtData = getdata
        } else { // 防止每次更新的淹没其他的
          //把没有的第一层数据存在，GetgiftData里面
          //把没有的第二层的数据存在, GetgiftData里面
          // spliceGetDataItem(getdata, state.getBgLmtData)
          // spliceGetDataTodo(getdata, state.getBgLmtData)
        }
      } else if (param.type == 2) {
        // compareSaleGift(state.bargainData, state.getBgUnLmtData)
        // compareOther(state.bargainData, state.getBgLmtData, [],'限制品牌')
        let getdata = JSON.parse(JSON.stringify(state.bargainData))
        getValueArray(getdata, { index: 'checked', childName: 'productSkuList', status: false })
        setEmptyArray(getdata, { index: 'checked', childName: 'productSkuList' })
        setArrayValue(getdata, { index: 'checked', val1: false, childName: 'productSkuList' })
        let paramData = {
          shelfStatusEnum: 'ON',
          joinTypeEnum: 'PART',
          startDate: formatDate(state.form.date[0], true),
          endDate: formatDate(state.form.date[1], true),
          productSkuList: getLimit(getdata, param.type == 1),
          distributorIdList: (state.form.distribedList || []).map(item => {
            return item.id
          }),
          distributorJoinTypeEnum: state.form.disribuType == '0' ? 'WHOLE' : 'PART'
        }
        if (!paramData.productSkuList.length) {
          Notice.warning({
            title: '温馨提示',
            desc: '请选择主商品加入不限制品牌'
          })
          return
        }
        saveProduct({
          productSkuList: paramData.productSkuList,
          activityId: param.id,
          self: param.self,
          type: param.type
        })
        // paramData.productSkuList.length && checkProduct(paramData)
        // if (getdata.length) {
        //   Notice.success({
        //     title: '温馨提示',
        //     desc: getProductData(getdata) + '加入非限制品牌成功'
        //   })
        // }
        if (!state.getBgUnLmtData.length) { //首次为空
          // state.getBgUnLmtData = getdata
        } else { // 防止每次更新的淹没其他的
          //把没有的第一层数据存在，GetgiftData里面
          //把没有的第二层的数据存在, GetgiftData里面
          // spliceGetDataItem(getdata, state.getBgUnLmtData)
          // spliceGetDataTodo(getdata, state.getBgUnLmtData)
        }
      }
    },
    setDistributData (state, data) {
      state.form.distribList = (data || []).map(item => {
        return {
          id: item.distributorId,
          value: item.distributorName,
          status: false
        }
      })
      deleteDistib(state)
    },
    setDelayDistributData (state, data) {
      state.form.delayDistribList = (data || []).map(item => {
        return {
          id: item.distributorId,
          value: item.distributorName,
          status: false,
          show: true
        }
      })
      console.log(state.form)
      deleteDistib(state, 'delay')
    },
    setPayDistributData (state, data) {
      state.form.payDistribList = (data || []).map(item => {
        return {
          id: item.distributorId,
          value: item.distributorName,
          status: false
        }
      })
      deleteDistib(state, 'pay')
    },
    setCouponsData (state, data) {
      state.form.couponsList = (data || []).map(item => {
        return {
          value: item.id,
          label: item.couponName
        }
      })
      state.form.couponsList.unshift({ value: '0', label: '不送' })
    },
    setfactoryTag (state, data) {
      state.form.factoryTag = data.map(item => {
        return {
          id: item.id,
          label: item.tagName
        }
      })
    },
    onChangeAllSelect (state, type) {
      let index = 'distribList'
      let index1 = 'distribedList'
      if (typeof (type) === 'string' && type === 'pay') {
        index = 'payDistribList'
        index1 = 'payDistribedList'
      }
      if (typeof (type) === 'string' && type === 'delay') {
        index = 'delayDistribList'
        index1 = 'delayDistribedList'
      }
      if (!state.form[index].length) return
      state.form[index1].push(...JSON.parse(JSON.stringify(state.form[index])))
      state.form[index1].forEach(item => {
        item.status = true
      })
      state.form[index] = []
    },
    onCancel (state, type) {
      let index = 'distribList'
      let index1 = 'distribedList'
      if (typeof (type) === 'string' && type === 'pay') {
        index = 'payDistribList'
        index1 = 'payDistribedList'
      }
      if (typeof (type) === 'string' && type === 'delay') {
        index = 'delayDistribList'
        index1 = 'delayDistribedList'
      }
      if (!state.form[index1].length) return
      state.form[index].push(...JSON.parse(JSON.stringify(state.form[index1])))
      state.form[index].forEach(item => {
        item.status = false
      })
      state.form[index1] = []
    },
    onBargainBatchInput (state, object) {
      let type = ''
      switch (object.dataType) {
        case '0':
          type = 'bargainData'
          break
        case '1':
          type = 'getBgLmtData'
          break
        case '2':
          type = 'getBgUnLmtData'
          break
      }
      setBatchData(state[type], object.value, object.type)
    },
    onBargainBatchSelect (state, object) {
      let type = ''
      switch (object.dataType) {
        case '0':
          type = 'bargainData'
          break
        case '1':
          type = 'getBgLmtData'
          break
        case '2':
          type = 'getBgUnLmtData'
          break
      }
      for (let item of state[type]) {
        if (item.checked) item['giftCouponId'] = object.id
        for (let todo of item.productSkuList) {
          if (todo.checked) todo['giftCouponId'] = object.id
        }
      }
    }
  },
  actions: {
    // 批量修改活动商品优惠券
    setCouponId ({ state, commit }, params) {
      let param = {
        activityId: params.activityId,
        ids: params.ids,
        giftCouponId: params.giftCouponId
      }
      return new Promise((resolve, reject) => {
        ajaxPost('/activity/sku/batch/gift_coupon_id', param).then(data => {
          resolve(data)
        })
      })
    },
    // 商品积分
    setGiftPoint ({ state, commit }, params) {
      let param = {
        activityId: params.activityId,
        ids: params.ids,
        giftPoint: params.giftPoint
      }
      return new Promise((resolve, reject) => {
        ajaxPost('/activity/sku/batch/gift_point', param).then(data => {
          resolve(data)
        })
      })
    },
    // 商品返利
    setGiftRebate ({ state, commit }, params) {
      let param = {
        activityId: params.activityId,
        ids: params.ids,
        giftRebate: params.giftRebate
      }
      return new Promise((resolve, reject) => {
        ajaxPost('/activity/sku/batch/gift_rebate', param).then(data => {
          resolve(data)
        })
      })
    },
    // 促销价
    setProQuantity ({ state, commit }, params) {
      let param = {
        activityId: params.activityId,
        ids: params.ids,
        promotionPrice: params.promotionPrice
      }
      return new Promise((resolve, reject) => {
        ajaxPost('/activity/sku/batch/promotion_price', param).then(data => {
          resolve(data)
        })
      })
    },
    // 促销库存
    setSellOutQuantity ({ state, commit }, params) {
      let param = {
        activityId: params.activityId,
        ids: params.ids,
        sellOutQuantity: params.sellOutQuantity
      }
      return new Promise((resolve, reject) => {
        ajaxPost('/activity/sku/batch/sell_out_quantity', param).then(data => {
          resolve(data)
        })
      })
    },
    getSkuCount ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        ajaxGet(`/activity/sku/count/${param.id}`, { isLimitBrand: param.isLimitBrand }).then(data => {
          if (param.isLimitBrand) {
            state.limitBrandNum = data
          } else {
            state.UnlimitBrandNum = data
          }
          resolve(data)
        })
      })
    },
    deleteSku ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        ajaxPost(`/activity/sku/del/batch`, { ids: param.id, activityId: param.activityId }).then(data => {
          resolve(data)
        })
      })
    },
    getShelfStatus ({ state, commit }, id) {
      return new Promise((resolve, reject) => {
        ajaxGet(`/activity/shelf_status/${id}`).then(data => {
          resolve(data)
        })
      })
    },
    getSkuPage ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        ajaxGet(`/activity/sku/page`, { activityId: param.activityId, isLimitBrand: param.isLimitBrand, current: param.current, size: param.size, storeCategoryId: state.searchForm.ownerCategoryId, productName: state.searchForm.keyword, productBrandId: state.searchForm.brandId }).then(data => {
          if (param.isLimitBrand) {
            state.getBgLmtData = setData(data)
            setItem(state.getBgLmtData, ['sellOutQuantity', 'giftRebate', 'giftPoint', 'sale'])
          } else {
            state.getBgUnLmtData = setData(data)
            setItem(state.getBgUnLmtData, ['sellOutQuantity', 'giftRebate', 'giftPoint', 'sale'])
          }
          let self = param.self

          self.status = 'pass'
          self.currentPage = Number(data.current)
          self.totalItem = Number(data.total)
          resolve(data)
        })
      })
    },
    getfactoryTag ({ state, commit }) {
      ajaxGet('/activity/tag/getAll').then(data => {
        commit('setfactoryTag', data)
      })
    },
    getDistributData ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        param && ajaxGet('/tiger/distributor/list', param).then(data => {
        // 支付方式设置 - type == 1
        // if (typeof params === String && params === '1') {
          if (!param.isSearch) commit('setPayDistributData', data)
          // } else {
          if (param.type === 'distribute') commit('setDistributData', data)
          if (param.type === 'delay') commit('setDelayDistributData', data)
          // }
          resolve(data)
        })
      })
    },
    // 通过科室地区获取经销商
    getDistributDataByDept ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        jsonPost('/department/queryDistributorDepartment', param).then(res => {
          let data = res.records
        // 支付方式设置 - type == 1
        // if (typeof params === String && params === '1') {
          if (!param.isSearch) commit('setPayDistributData', data)
          // } else {
          if (param.type === 'distribute') commit('setDistributData', data)
          if (param.type === 'delay') commit('setDelayDistributData', data)
          // }
          resolve(data)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    getCouponsData ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        ajaxGet('/coupon/coupon_info/factory_coupon', param).then(data => {
          commit('setCouponsData', data)
          resolve(data)
        })
      })
    },
    getPrucductData ({ state, commit }, param) {
      return new Promise((resolve, reject) => {
        ajaxGet('/activity/product/spu_sku_page', { current: param.current, size: param.size, ownerCategoryId: state.searchForm.ownerCategoryId, keyword: state.searchForm.keyword, code: state.searchForm.code, skuCode: state.searchForm.skuCode, brandId: state.searchForm.brandId }).then(data => {
          let self = param.self
          self.status = 'pass'
          resolve(data)
          self.currentPage = Number(data.current)
          self.totalItem = Number(data.total)
          state.bargainData = data.records
          setAdd(self, state.bargainData, { index: 'checked', val1: false, childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'showChildren', val1: false, childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'returnPrice', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'quantity', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'giftPoint', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'giftRebate', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'giftCouponId', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'sellOutQuantity', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'warningQuantity', val1: '', childName: 'productSkuList' })
          setAdd(self, state.bargainData, { index: 'sale', val1: '', childName: 'productSkuList' })
          getCode(self, state.bargainData, { index: 'parentcode', childName: 'productSkuList' })
        })
      })
    }
  },
  getters: {
    bargainRemindList: (state, getters) => {
      let word = ''
      state.form.phoneRemind.listRemind.forEach((item, index) => {
        let text = ''
        if (item.isRemind) {
          if (index == 0) {
            text = `活动开始前${item.time}小时：`
          } else if (index == 1) {
            text = '活动开始时：'
          } else if (index == 2) {
            text = `活动结束前${item.time}小时：`
          }
          word = word + text + item.text + '。'
        }
      })
      return word
    },
    bargainAllRemind: (state, getters) => {
      let status = '否'
      if (state.form.phoneRemind.allRemind) status = '是'
      return status
    },
    factoryMsgDTOList: (state, getters) => {
      let list = []
      let param = {}
      const getActiveTime = (index, time, remind) => {
        let newTime = ''
        let newIndex = ''
        let isRemind = ''
        if (index == 0) {
          newTime = formatDate(new Date(new Date(state.form.date[0]).getTime() - time * 3600 * 1000), true)
          newIndex = 'BEFORE'
        } else if (index == 1) {
          newTime = formatDate(state.form.date[0], true)
          newIndex = 'ING'
        } else if (index == 2) {
          newTime = formatDate(new Date(new Date(state.form.date[1]).getTime() - time * 3600 * 1000), true)
          newIndex = 'AFTER'
        }
        isRemind = remind ? 'ON' : 'OFF'
        param = {
          newTime: newTime,
          index: newIndex,
          isRemind: isRemind
        }
        return param
      }
      state.form.phoneRemind.listRemind.forEach((item, index) => {
        list.push({
          msgStatusEnum: getActiveTime(index, item.time, item.isRemind).isRemind,
          msgTypeEnum: getActiveTime(index, item.time, item.isRemind).index,
          msgContent: item.text,
          msgTime: getActiveTime(index, item.time, item.isRemind).newTime,
          msgHours: item.time
        })
      })
      return list
    },
    factoryTag: (state, getters) => {
      return state.form.factoryTag
    },
    allDistributor: (state, getters) => {
      return state.form.disribuType == '0'
    },
    bargainTag: (state, getters) => {
      let word = ''
      getters.factoryTag.forEach(item => {
        if (item.id == state.form.tag) {
          word = item.label
        }
      })
      return word
    },
    bargainName: (state, getters) => {
      return state.form.name
    },
    bargainGate: (state, getters) => {
      return state.form.propagate
    },
    bargainDate: (state, getters) => {
      return state.form.date
    },
    bargainIntegralDate: (state, getters) => {
      return state.form.integralDate
    },
    delayDate: (state, getters) => {
      return state.form.delayDate
    },
    bargainCouponsData: (state, getters) => {
      return state.form.couponsList
    },
    bargainStoreNum: (state, getters) => {
      return state.form.limitNum
    },
    // 已选
    bargainSelected: (state, getters) => {
      if (state.form.disribuType == '0') return []
      return state.form.distribedList
    },
    bargainSelectedDelay: (state) => {
      return state.form.delayDistribedList
    },
    // 当前
    bargainNoSelected: (state, getters) => {
      // return .filter(item => !item.status)
    },
    aFDList: (state, getters) => {
      if (state.form.disribuType == '0') return []
      return (getters.bargainSelected || []).map(item => {
        return {
          distributorId: item.id
        }
      })
    },
    dFDList: (state, getters) => {
      return (getters.bargainSelectedDelay || []).map(item => item.id)
    },
    // 支付指定经销商
    payDistributorIdList: (state, getters) => {
      if (state.form.payDistributorJoinType == 'WHOLE') return []
      return (state.form.payDistribedList || []).map(item => {
        return item.id
      })
    },
    filterstoreType: (state, getters) => {
      return state.form.list
    },
    storeTypeLimitNumberDTOList: (state, getters) => {
      let text = []
      state.form.list.forEach(item => {
        if (item.isChecked) {
          text.push({
            storeTypeEnum: item.value,
            limitNumber: item.num,
            totalLimitNumber: item.totalNum
          })
        }
      })
      return text
    },
    stroeTypeList: (state, getters) => {
      let word = ''
      state.form.list.map((item, index, array) => {
        if (item.num) {
          word = word + item.name + '(规格限购：' + (item.num ? item.num : '') + ',' + '总量限购：' + (item.totalNum ? item.totalNum : '') + ')' + (((array.length - 1) > index) ? '、' : '')
        } else if (!item.isChecked) {
          word = word + item.name + '不参与活动' + (((array.length - 1) > index) ? '、' : '')
        } else {
          word = word + item.name + '不限制' + (((array.length - 1) > index) ? '、' : '')
        }
      })
      return word
    },
    bargainLimiNum: (state, getters) => {
      // return getSaleNum(state.getBgLmtData, {
      //   childName: 'productSkuList'
      // })
      return state.limitBrandNum
    },
    bargainUnLimitNum: (state, getters) => {
      // return getSaleNum(state.getBgUnLmtData, {
      //   childName: 'productSkuList'
      // })
      return state.UnlimitBrandNum
    },
    bargainIsSet: (state, getters) => {
      return state.form.isSet == '0'
    },
    bargainDisribuType: (state, getters) => {
      return state.form.disribuType == '0'
    },
    bargainAllDistributor: (state, getters) => {
      return state.form.disribuType == '0'
    },
    bargainAllPayDistributor: (state, getters) => {
      return state.form.payDistributorJoinType == 'WHOLE'
    },
    bargainIsCurrencyNum: (state, getters) => {
      return state.form.isCurrencyNum == '0'
    },
    barginIsStore: (state, getters) => {
      return state.form.isStoreSet == '0'
    },
    exceptionalStoreDTOList: (state, getters) => {
      return (state.exceptionalStoreDTOList || []).map(item => {
        return {
          storeName: item.storeName,
          limitNum: item.limitNum
        }
      })
    },
    storeCount: (state, getters) => {
      return state.storeCount
    }
  }
})
